package com.haonan.springboot_exercise.netty.client;

import com.haonan.springboot_exercise.bean.pojo.MyMailMessage;
import com.haonan.springboot_exercise.bean.pojo.ServicePort;
import com.haonan.springboot_exercise.dao.SmtpServerDao;
import com.haonan.springboot_exercise.util.SpringUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * @author haonan
 * @date 2021/4/12 19:33
 **/
@Slf4j
@Component
@Order(value = 1)
public class SmtpClient implements Runnable{
    private SmtpClientInitializer smtpClientInitializer;
    private Object msg;
    private MyMailMessage myMailMessage;
    private Channel channel;
    private ChannelFuture channelFuture;
    private EventLoopGroup group;

    public void start() {
        smtpClientInitializer = new SmtpClientInitializer();
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap()
                .group(group)
                //该参数的作用就是禁止使用Nagle算法，使用于小数据即时传输
                .option(ChannelOption.TCP_NODELAY, true)
                .channel(NioSocketChannel.class)
                .handler(smtpClientInitializer);

        try {
            SmtpServerDao smtpServerDao = SpringUtil.getBean(SmtpServerDao.class);
            ChannelFuture future = bootstrap.connect("127.0.0.1", smtpServerDao.getSmtpPort("127.0.0.1")).sync();
            log.info("SMTP客户端成功....");
            channel = future.channel();
            channelFuture = future;
            this.group = group;
            //发送消息
            //这里需要用到SmtpClientMailService，把MyMailMessage类转化成String然后一条一条发过去
//            channel.writeAndFlush(msg);

            // 等待连接被关闭(在这里用会导致线程阻塞)
//            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

//        finally {
//            group.shutdownGracefully();
//        }
    }

    @Async//注意这里，组件启动时会执行run，这个注解是让线程异步执行，这样不影响主线程
    @Override
    public void run() {
        start();
    }

    public void setMsg(Object msg){
        this.msg = msg;
    }

    public Channel getChannel(){
        return channel;
    }

    public EventLoopGroup getGroup(){
        return group;
    }

    public MyMailMessage getMyMailMessage(){
        return myMailMessage;
    }

    public void setMyMailMessage(MyMailMessage myMailMessage){
        this.myMailMessage = myMailMessage;
    }

    public SmtpClientHandler getSmtpClientHandler(){
        return smtpClientInitializer.getSmtpClientHandler();
    }

}
